package com.g3net.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * 过滤登陆信息
 * 
 * @author liujinlong
 * 
 */
public class LoginFilter implements Filter {
	private static Logger log = Logger.getLogger(LoginFilter.class);

	////@Override
	public void destroy() {
		
	}

	////@Override
	public void doFilter(ServletRequest arg, ServletResponse arg0,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg;
		HttpServletResponse response = (HttpServletResponse) arg0;
		HttpSession session = request.getSession();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String username = (String)session.getAttribute("username");
		String password = (String)session.getAttribute("password");
		String currentURL = request.getRequestURI();// 取得根目录所对应的绝对路径:
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1),
				currentURL.length()); // 截取到当前文件名用于比较
		log.info("操作人员为"+username);
		if (!"/webcontent/index.jsp".equals(targetURL) && !"/".equals(targetURL.trim()) &&  targetURL != null && !"".equals(targetURL)) {
		//防止由于重复请求页面也造成循环访问index.jsp
			if (session == null || session.getAttribute("username") == null
					|| session.getAttribute("password") == null) {
				log.info("targetURL:"+targetURL+";req.getContextPath():"+request.getContextPath());
				response.sendRedirect(request.getContextPath());
				return;
			}
		}
		filterChain.doFilter(request, response);
	}

	////@Override
	public void init(FilterConfig arg0) throws ServletException {
		arg0.getServletContext();
	}
}